﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;

namespace MiniBug.Controllers
{
    [HandleError]
    public class BugController : Controller
    {
        //
        // GET: /Bug/
        private Entity.MSSQLEntity dbContext = new Entity.MSSQLEntity();

        [ValidateAntiForgeryToken()]
        [OutputCache(Duration = 10, VaryByParam = "none")]
        public ActionResult Index()
        {

            return View(dbContext.Bug.ToList());
        }



        [ValidateAntiForgeryToken()]
        public PartialViewResult List()
        {

            return PartialView(dbContext.Bug.ToList());
        }

        //
        // GET: /Bug/Details/5

        [ValidateAntiForgeryToken()]
        public ActionResult Details(int id)
        {
            var bug = (from p in dbContext.Bug
                          where p.idBug == id
                          select p).FirstOrDefault();
            bug.Views += 1;
            dbContext.ApplyCurrentValues(bug.EntityKey.EntitySetName,bug);
            dbContext.SaveChanges();
            return View();
        }

        //
        // GET: /Bug/Create
       
        //[ValidateAntiForgeryToken()]
        [Authorize]
        public ActionResult Create()
        {
            Random rnd = new Random();
            ViewData["BugNumber"] = GetNextBugNumber().ToString().PadLeft(4, '0');
            ViewData["ProjectList"] = GetProjectList();
            ViewData["CategoryList"] = GetCategoryList();
            ViewData["StatusList"] = GetStatusList();
            ViewData["PriorityList"] = GetPriorityList();
            ViewData["AssignedTo"] = GetAllUsers();
            ViewData["UserList"] = GetCurrentUser();
            return View();
        }

        private SelectList GetCurrentUser()
        {
            List<string> items = new List<string>();
            using (Entity.MSSQLEntity dbContext = new Entity.MSSQLEntity())
            {

                var user = (from p in dbContext.User
                            where p.Login == HttpContext.User.Identity.Name
                            select p).FirstOrDefault();
                if (user != null)
                {
                    items.Add(user.Name);
                }
            }

            SelectList users = new SelectList(items);

            return users;
        }

        private SelectList GetAllUsers()
        {
            return new SelectList(dbContext.User, "idUser", "Name",1);
        }


        private SelectList GetProjectList()
        {
            int projCount = dbContext.Project.Count();

            if (projCount <= 0)
            {
                Entity.Project proj = new Entity.Project();
                proj.Name = "NoProject";
                dbContext.AddToProject(proj);
                dbContext.SaveChanges();
            }

            SelectList projects = new SelectList(dbContext.Project, "idProject", "Name", 1);

            return projects;
        }

        private SelectList GetCategoryList()
        {
            List<string> items = new List<string>();
            items.Add(ResourceModels.CategoryStrings.Bug);
            items.Add(ResourceModels.CategoryStrings.Feature);
            items.Add(ResourceModels.CategoryStrings.Activity);
            SelectList categories = new SelectList(items);
            return categories;
        }

        private SelectList GetStatusList()
        {
            List<string> items = new List<string>();
            items.Add( ResourceModels.StatusStrings.Opened);
            items.Add(ResourceModels.StatusStrings.Closed);
            items.Add( ResourceModels.StatusStrings.Resolved);
            items.Add( ResourceModels.StatusStrings.Assigned);
            SelectList status = new SelectList(items);
            return status;
        }

        private SelectList GetPriorityList()
        {
            List<string> items = new List<string>();
            items.Add(ResourceModels.PriorityStrings.MustFix);
            items.Add(ResourceModels.PriorityStrings.FixIfTime);
            items.Add(ResourceModels.PriorityStrings.DoNotFix);
            SelectList status = new SelectList(items);
            return status;
        }      




        //
        // POST: /Bug/Create

        [HttpPost]
        [Authorize]
        //[ValidateAntiForgeryToken()]
        public ActionResult Create([Bind(Exclude = "idBug")] Entity.Bug newBug, FormCollection form)
        {
            try
            {
                int number;
                int.TryParse(ViewData["BugNumber"].ToString(), out number);
                newBug.Number = number;
                newBug.OpenDate = DateTime.Now;
                newBug.Description = Server.HtmlEncode(newBug.Description);

                int userID = int.Parse(form["UserList"]); 
                int projectID = int.Parse(form["ProjectList"]);
                int priorityID = int.Parse(form["PriorityList"]);
                int categoryID = int.Parse(form["CategoryList"]);

                List<Entity.BugAttachment> attachList = GetAttachments();

                foreach (Entity.BugAttachment item in attachList)
                {
                    newBug.Attachments.Add(item);
                }

                string[] tags = GetTags(form);

                foreach (string tag in tags)
                {
                    Entity.BugTag newTag = new Entity.BugTag();
                    newTag.tag = tag;
                    newBug.Tags.Add(newTag);
                }

                newBug.idOwner = userID;
                newBug.idProject = projectID;
                newBug.idPriority = priorityID;
                newBug.idCategory = categoryID;
                newBug.idAssignedTo = userID;

                dbContext.AddToBug(newBug);
                dbContext.SaveChanges();

               

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        private int GetNextBugNumber()
        {
            int number = 0;
            if (dbContext.Bug.Count() > 0)
            {
                number = dbContext.Bug.Where(b => b.Number != null).Max(b => b.Number);
                
            }
            number++;
            return number;
        }


        private static string[] GetTags(FormCollection form)
        {
            string[] tags = form["Tags"].Split(' ');
            return tags;
        }

        private List<Entity.BugAttachment> GetAttachments()
        {
            List<Entity.BugAttachment> list = new List<Entity.BugAttachment>();
            for (int i = 0; i < Request.Files.Count; i++)
            {
                HttpPostedFileBase file = Request.Files[i];
                Entity.BugAttachment attach = new Entity.BugAttachment();
                byte[] buffer = new byte[file.ContentLength];
                file.InputStream.Read(buffer, 0, file.ContentLength);
                attach.data = buffer;
                list.Add(attach);
            }
            return list;
        }

        //
        // GET: /Bug/Edit/5
        [Authorize]
        [ValidateAntiForgeryToken()]
        public ActionResult Edit(int id)
        {
            var result = (from p in dbContext.Bug
                          where p.idBug == id
                          select p).FirstOrDefault();
            return View(result);
        }

        //
        // POST: /Bug/Edit/5

        [HttpPost]
        [Authorize]
        [ValidateAntiForgeryToken()]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Bug/Delete/5
        [Authorize]
        [ValidateAntiForgeryToken()]
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Bug/Delete/5

        [HttpPost]
        [Authorize]
        [ValidateAntiForgeryToken()]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

    }
}
